﻿using CefSharp.WinForms;
using Newtonsoft.Json;
using SmartlForm;
using SmartlForm.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartForm.NetJs
{
    public partial class ChromeJs
    {
        public ChromiumWebBrowser _instanceBrowser = null;
        public Form _instanceMainForm = null;

        public ChromeJs(ChromiumWebBrowser originalBrowser, Form mainForm)
        {
            _instanceBrowser = originalBrowser;
            _instanceMainForm = mainForm;
        }

        /// <summary>
        /// 执行JS（不会返回执行结果）
        /// </summary>
        /// <param name="js"></param>
        public void ExeScript(string js)
        {
            if (!_instanceBrowser.IsDisposed)
            {
                _instanceBrowser.GetBrowser().MainFrame.ExecuteJavaScriptAsync(js);
            }
        }

        /// <summary>
        /// 执行JS并返回执行结果
        /// </summary>
        /// <param name="js"></param>
        /// <returns></returns>
        public object ExeScriptResult(string js)
        {
            if (!_instanceBrowser.IsDisposed)
            {
                var task = _instanceBrowser.GetBrowser().MainFrame.EvaluateScriptAsync(js);
                object result = null;
                task.ContinueWith(t =>
                {
                    if (!t.IsFaulted)
                    {
                        var response = t.Result;
                        result = response.Success ? (response.Result ?? "null") : response.Message;
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
                return result;
            }
            else
            {
                return null;
            }
        }


        public delegate void MethodInvokerPar3(string par1, string par2, string par3);
        public delegate void MethodInvokerPars(params string[] pars);
        public delegate void MethodInvokerFormPars(object pars);


        /// <summary>
        /// 关闭
        /// </summary>
        public void exit()
        {
            if (_instanceMainForm.Name.Equals("app"))
            {
                Application.Exit();
            }
            else
            {
                _instanceMainForm.Close();
            }
        }

        #region 窗体跳转 

        public string getFormParDemo()
        {
            return JsonConvert.SerializeObject(new FormPar() { title = "测试", url = "\\\\page\\\\index.html", width = 480, height = 600, max = false });
        }

        public void openForm(object par)
        {
            _instanceMainForm.BeginInvoke(new MethodInvokerFormPars(OpenForm), par);
        }

        private void OpenForm(object par)
        {
            string json = JsonConvert.SerializeObject(par);
            FormPar fp = JsonConvert.DeserializeObject<FormPar>(json);
            BowContainer settingForm = new BowContainer(JsonConvert.DeserializeObject<FormPar>(json));
            settingForm.Show();
            if (!string.IsNullOrEmpty(fp.successFunc))
            {
                ExeScript(fp.successFunc + "('" + fp.name + "')");
            }
        }
        #endregion
    }
}
